<template>
  <div>
      <input type="file" class="file" ref="file" @change="uploadAvatar">
      <img :src="pic" alt="" class="avatar" @click="handleClick">
  </div>
</template>
<script>
import {uploadpic} from "@/api"
import {axios,baseURL} from "@/utils/axios"
export default {
    props:['userinfo'],
    data(){
        return{
            pic:require("@/assets/images/head2.jpg")
        }
    },
    mounted(){
        if(this.userinfo){
           if(this.userinfo.avatar){
                this.pic = this.userinfo.avatar.replace(/public/,baseURL)
           }else{
               this.pic=require("@/assets/images/head2.jpg")
           }
        }else{
            this.pic=require("@/assets/images/head2.jpg")
        }

    },
    methods:{
        handleClick(){
            this.$refs.file.click()  //点击文件最终执行handlClick事件
        },
        uploadAvatar(){
            console.log("开始上传")
             console.log(this.$refs.file.files[0]) //发送后台
              var file = this.$refs.file.files[0]

            //创建表单对象
            var data = new FormData()
            data.append("avatar",file)

        uploadpic(data)
        .then(res=>{
            if(res.data.type){
               this.pic = res.data.avatar.replace(/public/,baseURL) //图片地址优化
            }
            

        })

        }
    }
}
</script>
<style lang="scss">
  .avatar{
      width: 45px;
      height: 45px;
      border-radius: 50%;
      cursor: pointer;
  }
  .file{
      display: none;
  }
</style>